package com.sunwayhorizo.health.business.patad.encounter;

import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.Query;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.BaseManager;
import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.business.dto.patad.empi.InfoInsuranceDTO;
import com.sunwayhorizo.health.business.dto.patad.empi.MedicalCardDTO;
import com.sunwayhorizo.health.business.dto.patad.empi.PatientBaseInfoDTO;
import com.sunwayhorizo.health.business.dto.patad.empi.PatientQueryDTO;
import com.sunwayhorizo.health.business.dto.patad.encounter.PatientEncounterDTO;
import com.sunwayhorizo.health.business.dto.registries.EntitysDTO;
import com.sunwayhorizo.health.business.dto.registries.VisitsDTO;
import com.sunwayhorizo.health.business.patad.empi.PatientManagerLocal;
import com.sunwayhorizo.health.business.patad.empi.query.PatientQueryLocal;
import com.sunwayhorizo.health.business.registries.employee.EmployeeManagerLocal;
import com.sunwayhorizo.health.business.registries.person.PersonManagerLocal;
import com.sunwayhorizo.health.business.registries.visits.VisitsManagerLocal;
import com.sunwayhorizo.health.common.DataTypeUtil;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.CE;
import com.sunwayhorizo.health.hl7.datatypes.II;
import com.sunwayhorizo.health.hl7.datatypes.SET_II;
import com.sunwayhorizo.health.hl7.persistent.RimCoreActPrtcptns;
import com.sunwayhorizo.health.hl7.rim.Act;
import com.sunwayhorizo.health.hl7.rim.ActParticipation;
import com.sunwayhorizo.health.hl7.rim.ControlAct;
import com.sunwayhorizo.health.hl7.rim.Employee;
import com.sunwayhorizo.health.hl7.rim.Patient;
import com.sunwayhorizo.health.hl7.rim.PatientEncounter;
import com.sunwayhorizo.health.hl7.rim.Person;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.ActCode;
import com.sunwayhorizo.health.hl7.vocabulary.ActMood;
import com.sunwayhorizo.health.hl7.vocabulary.ActRelationshipType;
import com.sunwayhorizo.health.hl7.vocabulary.ActStatus;
import com.sunwayhorizo.health.hl7.vocabulary.ParticipationType;
import com.sunwayhorizo.health.hl7.vocabulary.RoleClass;

/**
 * 
 * @ClassName CheckinManager <br>
 * @PackageName com.sunwayhorizo.health.business.patad.encounter <br>
 * @Description 患者挂号 <br>
 * @Author jinzw <br>
 * @Date 2011-1-2 <br>
 * @Version 1.0 <br>
 * @ModifiedDesc <br>
 * @ModifiedDate <br>
 * @ModifiedBy <br>
 * @Email jinzw@sunwaysoft.com.cn <br>
 * @Copyright 2010-2020 horizo All Rights Reserved. <br>
 */
@Name("CheckinManager")
@Stateless
public class CheckinManager extends BaseManager implements CheckinManagerLocal
{

    private PatientQueryLocal patientQuery = (PatientQueryLocal) Component.getInstance("PatientQuery");


    public ResultsDTO newCheckIn(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        if (null == patientEncounterDTO)
        {
            return this.getResultsDTO("挂号失败，patientEncounterDTO为null", false, null);
        }
        PatientEncounterDTO patientEncouter = persistCheckIn(patientEncounterDTO);
        log.info("CheckinManager-persistPatient挂号成功");
        return this.getResultsDTO("挂号成功", true, patientEncouter);
    }


    public ResultsDTO transferClinic(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        PatientEncounterDTO patientEncounter = null;
        if (ListUtil.isNotEmpty(patientEncounterDTO.listVisitInfo))
        {
            CheckinManagerLocal patientEncounterAction = (CheckinManagerLocal) Component.getInstance("CheckinManager");
            List<VisitsDTO> listVisitsDTO = patientEncounterDTO.getListVisitInfo();
            if (ListUtil.isNotEmpty(listVisitsDTO))
            {
                for (VisitsDTO visitsDTO : listVisitsDTO)
                {
                    // 转号过程中写入费用明细

                    if (StrUtil.isNotEmpty(visitsDTO.getEncounterNO()))
                    {
                        patientEncounterAction.backNO(patientEncounterDTO);
                    }
                    else
                    {
                        patientEncounter = patientEncounterAction.persistCheckIn(patientEncounterDTO);
                        log.info("CheckinManager-transferClinic转号成功");
                    }
                }
            }
        }
        return this.getResultsDTO("转号成功", true, patientEncounter);
    }


    public ResultsDTO backNO(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        if (ListUtil.isNotEmpty(patientEncounterDTO.listVisitInfo))
        {
            CheckinManagerLocal patientEncounterAction = (CheckinManagerLocal) Component.getInstance("CheckinManager");
            for (VisitsDTO visitsInfoDTO : patientEncounterDTO.listVisitInfo)
            {
                if (StrUtil.isNotEmpty(visitsInfoDTO.getEncounterNO()))
                {
                    // 退号过程中写入费用明细

                    RimCoreActPrtcptns actPrtcptns = patientEncounterAction.findCheckInByEncounterNo(visitsInfoDTO.getEncounterNO());
                    // 根据就诊号得到挂号动作
                    PatientEncounter patientEncounterAct = patientEncounterAction.findCheckInById(null,
                        String.valueOf(actPrtcptns.getParticipationAct().getActId()), null);
                    if (patientEncounterAct != null)
                    {
                        // 退号为挂号挂号状态为ACTIVE的
                        if (patientEncounterAct.getStatusCode().equals(ActStatus.ACTIVE))
                        {
                            patientEncounterAct.setStatusCode(ActStatus.CANCELLED);
                            em.merge(patientEncounterAct);
                            log.info(visitsInfoDTO.getEncounterNO() + "退号成功");
                        }
                    }
                }
            }
        }
        log.info("CheckinManager-backNO退号成功");
        return this.getResultsDTO("退号成功", true, null);
    }


    @SuppressWarnings("unused")
    public ResultsDTO findPatientByMedCard(String medicalCardId) throws Hl7Exception
    {
        PatientEncounterDTO patientEncounter = new PatientEncounterDTO();
        PatientManagerLocal patientManager = (PatientManagerLocal) Component.getInstance("PatientManager");

        PatientQueryDTO patientQueryDTO = new PatientQueryDTO();
        patientQueryDTO.setMedicalCardId(medicalCardId);
        Patient patient = patientQuery.findPatientByNeturalId(medicalCardId);

        convertPatientInfo(patient, patientEncounter);// 构造患者基本信息

        if (patientEncounter != null)
        {
            log.info("CheckinManager-findPatientByMedCard查找患者信息成功");
            log.info("患者信息" + patientEncounter);
            return this.getResultsDTO("成功查询到患者基本信息", true, patientEncounter);
        }
        else
        {
            log.info("CheckinManager-findPatientByMedCard没有找到患者信息");
            return this.getResultsDTO("没有找到患者信息", true, null);
        }
    }


    public ResultsDTO findCheckInDetail(String encounterNo) throws Hl7Exception
    {
        if (StrUtil.isNotEmpty(encounterNo))
        {
            ActParticipation actPrtcptns = findCheckInByEncounterNo(encounterNo);
            PatientEncounterDTO patientEncounter = null;
            if (actPrtcptns != null)
            {
                patientEncounter = convertPatientEncounterDTO((Act) actPrtcptns.getParticipationAct(), actPrtcptns);
                log.info("CheckinManager-findCheckInDetail根据就诊序号" + encounterNo + "查询成功");
                return this.getResultsDTO("据就诊序号查询成功", true, patientEncounter);
            }
            else
            {
                log.info("CheckinManager-findCheckInDetail根据就诊序号" + encounterNo + "查询没有数据");
                return this.getResultsDTO("该就诊序号没有找到挂号信息", true, null);
            }

        }
        else
        {
            log.info("CheckinManager-findCheckInDetail就诊序号为空，没有查询结果");
            return this.getResultsDTO("就诊序号为空，没有查询结果", true, null);
        }
    }


    @SuppressWarnings({ "rawtypes", "unchecked" })
    public PatientEncounterDTO persistCheckIn(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        String extenID = em.createNativeQuery("select EXTEN_CODE.NEXTVAL from dual").getResultList().get(0).toString();
        CE ce = null;
        Patient patient = null;
        Role visitsRole = null;
        Employee empRole = null;
        CE code = null;
        List<Map<Role, Long>> visitList = new ArrayList<Map<Role, Long>>();
        PatientEncounter patientEncounterAct = null;
        String encounterId = "enc" + extenID;
        II regIi = (II) DataTypeUtil.getSet_II(root, encounterId, "true", ActCode.CLINIC.code().stringValue());// 就诊号，后期统一生成就诊号

        if (ListUtil.isNotEmpty(patientEncounterDTO.getListVisitInfo()))
        {
            for (VisitsDTO visitInfo : patientEncounterDTO.getListVisitInfo())
            {
                if (StrUtil.isEmpty(visitInfo.getEncounterNO()))
                {
                    if (StrUtil.isNotEmpty(visitInfo.getVisitsId()))
                    {
                        visitsRole = baseQuery.findRoleById(Long.valueOf(visitInfo.getVisitsId()));
                        if (visitsRole != null)
                        {
                            Map<Role, Long> map = new HashMap<Role, Long>();
                            Long seqNum = this.findCountEncounter(String.valueOf(visitsRole.getRoleId())) + 1;
                            map.put(visitsRole, seqNum);
                            visitList.add(map);
                            log.info("成功得到号表角色");
                        }
                        else
                            log.info("号表角色为空，号表id为：" + visitInfo.getVisitsId());
                    }
                }
            }
        }
        if (StrUtil.isNotEmpty(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId()))
        {
            PatientQueryDTO patientQueryDTO = new PatientQueryDTO();
            patientQueryDTO.setPatientId(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
            patient = patientQuery.findPatientByNeturalId(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
            if (patient != null)
            {
                log.info("成功得到患者角色");
            }
            else
            {
                log.info("患者角色为空");
            }
        }
        else
        {
            // 保存患者信息到患者主索引
            String natureId = persistPatient(patientEncounterDTO);
            PatientQueryDTO patientQueryDTO = new PatientQueryDTO();
            patientQueryDTO.setPatientId(natureId);
            patient = patientQuery.findPatientByNeturalId(natureId);
            if (patient != null)
            {
                log.info("成功得到保存后患者角色");
            }
            else
            {
                log.info("保存后患者角色为空");
            }
        }

        // 判断操作员是否为空
        if (StrUtil.isNotEmpty(patientEncounterDTO.getLoginBaseInfo().getOperateId()))
        {
            EmployeeManagerLocal employeeAction = (EmployeeManagerLocal) Component.getInstance("EmployeeManager");
            empRole = employeeAction.findEmployeeDetail(Long.parseLong(patientEncounterDTO.getLoginBaseInfo().getOperateId()), null);
            if (empRole != null)
            {
                log.info("成功得到操作员角色");
            }
            else
            {
                log.info("操作员角色为空");
            }
        }

        SET_II controlActIi = DataTypeUtil.getSet_II(root, "controlAct" + extenID, "true", "CACT");
        ControlAct controlAct = this.getActFactory().newControlActEvent(ce, controlActIi);

        code = this.getDataTypeFactory().newCE(ActCode.CLINIC.code().toString());
        patientEncounterAct = this.getActFactory().newPatientEncounter(ActMood.APT, code, null);
        // patientEncounterAct.setPeVisitType(DataTypeUtil.getCE(BusinessConstants.CLINIC));
        log.info("构建挂号");

        controlAct.addOBActRelationship(ActRelationshipType.SUBJ, patientEncounterAct);

        // 完成一次门诊挂号
        if (empRole != null && patient != null && ListUtil.isNotEmpty(visitList))
        {
            if (patientEncounterAct != null)
            {
                // 保存就诊号
                patientEncounterAct.setId(regIi);
                // 保存挂号动作
                patientEncounterAct.setStatusCode(ActStatus.ACTIVE);
                // 保存费别
                if (StrUtil.isNotEmpty(patientEncounterDTO.getChargeTypeDic().getConceptCode()))
                {
                    CE chargeType = this.getDataTypeFactory().newCE(patientEncounterDTO.getChargeTypeDic().getConceptCode(),
                        patientEncounterDTO.getChargeTypeDic().getCodingschemeOid(), patientEncounterDTO.getChargeTypeDic().getCodingschemeEnName(),
                        patientEncounterDTO.getChargeTypeDic().getCodingschemeChName(), patientEncounterDTO.getChargeTypeDic().getConceptName(),
                        patientEncounterDTO.getChargeTypeDic().getVersionName());
                    patientEncounterAct.setChargeType(chargeType);
                }
                patientEncounterAct.addPartWithOutEntRole(ParticipationType.ADM, empRole);
                patientEncounterAct.addPartWithOutEntRole(ParticipationType.SBJ, patient);
                for (int j = 0; j < visitList.size(); j++)
                {
                    Map<Role, Long> map = visitList.get(j);
                    Set<Entry<Role, Long>> set = map.entrySet();
                    for (Iterator i = set.iterator(); i.hasNext();)
                    {
                        Map.Entry<Role, Long> m = (Map.Entry<Role, Long>) i.next();
                        visitsRole = m.getKey();
                        Long seqNum = m.getValue();
                        if (visitsRole != null)
                        {
                            ActParticipation participation = new ActParticipation();
                            participation.setTypeCode(ParticipationType.SDLOC);
                            participation.setEncouterNo(DataTypeUtil.getCS(encounterId + j)); // 就诊序号

                            participation.setSequenceNumber(DataTypeUtil.getINT(seqNum)); // 当前号
                            patientEncounterAct.addParticipation(ParticipationType.SDLOC, visitsRole);
                            log.info(visitsRole.getRoleId() + "号表参与到挂号动作中");
                        }
                        else
                        {
                            log.info("号表为空不能参与到挂号动作中");
                        }
                    }
                }
                em.persist(controlAct);
            }
        }

        PatientEncounterDTO patientEncouter = convertPatientEncounterDTO(patientEncounterAct, null);
        return patientEncouter;
    }


    public PatientEncounterDTO convertPatientEncounterDTO(Act act, ActParticipation actPrtcptns) throws Hl7Exception
    {
        if (null == act)
            return null;
        PatientEncounterDTO patientEncounter = new PatientEncounterDTO();
        List<ActParticipation> actPrtcptnsList = act.getParticipations();
        if (ListUtil.isNotEmpty(actPrtcptnsList))
        {
            List<VisitsDTO> visisList = new ArrayList<VisitsDTO>();
            for (ActParticipation actPrtcptnss : act.getParticipations())
            {
                ActParticipation actPrtcptn = (ActParticipation) actPrtcptnss;
                Role role = (Role) actPrtcptn.getRoleparticipation();
                if (role.getClassCode().code().toString().equals(RoleClass.PAT.code().toString()))
                {
                    Patient patient = (Patient) role;
                    convertPatientInfo(patient, patientEncounter);// 构造患者基本信息
                }
                if (actPrtcptns != null)
                {
                    // 拿到号表信息
                    if (actPrtcptns.getEncouterNo().equals(actPrtcptn.getEncouterNo()))
                    {
                        if (role.getClassCode().code().toString().equals(RoleClass.CLINICINDEX.code().toString()))
                        {
                            VisitsManagerLocal visitsManager = (VisitsManagerLocal) Component.getInstance("VisitsManager");
                            VisitsDTO visitsDTO = visitsManager.convertVisitsDTO(role);
                            visisList.add(visitsDTO);
                            visitsDTO.setEncounterNO(actPrtcptn.getEncouterNo().code().toString());// 就诊序号
                        }
                    }
                }
                else
                {
                    if (role.getClassCode().code().toString().equals(RoleClass.CLINICINDEX.code().toString()))
                    {
                        VisitsManagerLocal visitsManager = (VisitsManagerLocal) Component.getInstance("VisitsManager");
                        VisitsDTO visitsDTO = visitsManager.convertVisitsDTO(role);
                        visisList.add(visitsDTO);
                        visitsDTO.setEncounterNO(actPrtcptn.getEncouterNo().code().toString());// 就诊序号
                    }
                }

            }
            patientEncounter.setListVisitInfo(visisList); // 号表集合
            // patientEncounter.setEncounterID(act.getActsIiList().get(0).getExtensionTxt());
            // //就诊号
            // act.getActCdSetsIiList();
            // patientEncounter.setChargeTypeDic(this.getDictionaryFactory().convertActCdSets(act.getActCdSetsIiList().get(0)));
        }
        return patientEncounter;
    }


    @SuppressWarnings("unchecked")
    public Long findCountEncounter(String visitId) throws Hl7Exception
    {
        List<Long> list = null;
        StringBuilder jbql = new StringBuilder();
        if (!StrUtil.isEmpty(visitId))
        {
            jbql.append("select count(rp.participationId) from RimCoreActPrtcptns rp where rp.roleParticipation.roleId=?1 and rp.typeCode='SDLOC'");
        }
        Query query = em.createQuery(jbql.toString());
        if (!StrUtil.isEmpty(visitId))
        {
            query.setParameter(1, Long.parseLong(visitId));
        }
        list = query.getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            log.info("CheckinManager-findCountEncounter" + visitId + "号表已挂" + list.get(0).longValue() + "个患者");
            return list.get(0).longValue();

        }
        return new Long(0);
    }


    public ActParticipation findCheckInByEncounterNo(String encounterNo) throws Hl7Exception
    {
        if (StrUtil.isEmpty(encounterNo))
            return null;
        StringBuilder jbql = new StringBuilder();
        jbql.append("select rp from ActParticipation rp where rp.encounterNO=?1 and rp.participationAct.statusCode='active'");
        Query query = em.createQuery(jbql.toString());
        query.setParameter(1, encounterNo);
        @SuppressWarnings("unchecked")
        List<ActParticipation> list = query.getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            return list.get(0);
        }
        return null;
    }


    public void convertPatientInfo(Patient patient, PatientEncounterDTO patientEncounter) throws Hl7Exception
    {
        if (patient == null)
            return;
        Person person = (Person) patient.getPlayerEntities();
        PersonManagerLocal personManager = (PersonManagerLocal) Component.getInstance("PersonManager");
        PatientBaseInfoDTO patientBaseInfo = personManager.constructorPatBaseInfo(person);
        patientEncounter.setPatientBaseInfoDTO(patientBaseInfo);
        // 取出身份证
        // List<MedicalCardDTO> list = personManager.getMedicalCardList(person);
        // if (ListUtil.isNotEmpty(list)) {
        // for (MedicalCardDTO medicalCard : list) {
        // if (medicalCard.getTypeDic().getConceptCode()
        // .equals(EntityIICode.IDENTITYCARD.getConceptCode())) {
        // patientEncounter.setCardTypeDic(medicalCard.getTypeDic());
        // patientEncounter.setCardId(medicalCard.getId());
        // }
        // }
        // }
        // 得到医保信息
        // List<InfoInsuranceDTO> infoInsuranceList = personManager
        // .getInfoInsuranceList(patient, patientBaseInfo);
        // if (ListUtil.isNotEmpty(infoInsuranceList)) {
        // for (InfoInsuranceDTO infoInsuranceDTO : infoInsuranceList) {
        // if (infoInsuranceDTO.getState().equals("true")) {
        // patientEncounter.setInsuranceId(infoInsuranceList.get(0)
        // .getId());
        // patientEncounter.setInsuranceTypeDic(infoInsuranceList.get(
        // 0).getTypeDic());
        // }
        // }
        // }
    }


    /**
     * 保存一个患者
     * 
     * @param patientEncounterDTO
     * @return
     * @throws Hl7Exception
     */
    public String persistPatient(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        EntitysDTO entityDto = new EntitysDTO();
        entityDto.getPatientBaseInfo().setNatureName(patientEncounterDTO.getPatientBaseInfoDTO().getNatureName());
        entityDto.getPatientBaseInfo().setNatureBirthdate(patientEncounterDTO.getPatientBaseInfoDTO().getNatureBirthdate());
        entityDto.getPatientBaseInfo().setNatureSexDic(patientEncounterDTO.getPatientBaseInfoDTO().getNatureSexDic());
        entityDto.getPatientBaseInfo().setPersonId(patientEncounterDTO.getPatientBaseInfoDTO().getPersonId());

        List<MedicalCardDTO> medicalCardList = new ArrayList<MedicalCardDTO>();
        List<InfoInsuranceDTO> insuranceList = new ArrayList<InfoInsuranceDTO>();
        if (StrUtil.isNotEmpty(patientEncounterDTO.getMedicalCardId()))
        {
            MedicalCardDTO medicalCardDTO = new MedicalCardDTO();
            medicalCardDTO.setId(patientEncounterDTO.getMedicalCardId());
            medicalCardDTO.setTypeDic(patientEncounterDTO.getMedicalCardTypeDic());
            medicalCardList.add(medicalCardDTO);
        }
        if (StrUtil.isNotEmpty(patientEncounterDTO.getCardId()))
        {
            MedicalCardDTO cardDTO = new MedicalCardDTO();
            cardDTO.setId(patientEncounterDTO.getCardId());
            cardDTO.setTypeDic(patientEncounterDTO.getCardTypeDic());
            medicalCardList.add(cardDTO);
        }
        entityDto.setListMedicalCard(medicalCardList);
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInsuranceId()))
        {
            InfoInsuranceDTO infoInsurance = new InfoInsuranceDTO();
            infoInsurance.setId(patientEncounterDTO.getInsuranceId());
            infoInsurance.setTypeDic(patientEncounterDTO.getInsuranceTypeDic());
            infoInsurance.setState("true");
            insuranceList.add(infoInsurance);
        }
        entityDto.setListInsurance(insuranceList);

        PatientManagerLocal manager = (PatientManagerLocal) Component.getInstance("PatientManager");

        String patientId = manager.newPatientIndex(entityDto).getObject().toString();
        log.info("CheckinManager-persistPatient" + patientId + "患者保存成功");
        return patientId;
    }


    @SuppressWarnings("unchecked")
    public List<PatientEncounter> findCheckInByCond(String encounterId, String actId, String entounterType) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append("select pe from PatientEncounter pe ");
        String cond = " where 1=1 ";
        if (StrUtil.isNotEmpty(encounterId) && StrUtil.isNotEmpty(entounterType))
        {
            jbql.append(" LEFT JOIN pe.actsIiList peIi");
            cond += " and peIi.extensionTxt=?1 and peIi.identifierName=?3 ";
        }
        if (StrUtil.isNotEmpty(actId))
        {
            cond += " and pe.actId = ?2";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(encounterId))
        {
            query.setParameter(1, encounterId);
        }
        if (StrUtil.isNotEmpty(entounterType))
        {
            query.setParameter(3, entounterType);
        }
        if (StrUtil.isNotEmpty(actId))
        {
            query.setParameter(2, Long.parseLong(actId));
        }
        List<PatientEncounter> list = query.getResultList();
        return list;
    }


    public PatientEncounter findCheckInById(String encounterId, String actId, String entounterType) throws Hl7Exception
    {
        List<PatientEncounter> list = findCheckInByCond(encounterId, actId, entounterType);
        if (ListUtil.isNotEmpty(list))
        {
            return list.get(0);
        }
        return null;
    }


    @SuppressWarnings({ "rawtypes" })
    public ResultsDTO findCheckInList(String personId, List workGroupIds, String encounterType) throws Hl7Exception
    {
        /*
         * StringBuilder jbql = new StringBuilder();
         * jbql.append("select rp from RimCoreActPrtcptns rp");
         * //jbql.append(" LEFT JOIN rp.roleParticipation rpp"); String cond =
         * " where rp.participationAct.codeEtsId=?1 and rp.participationAct.statusCode='active'"
         * ; if(StrUtil.isNotEmpty(deptId)) { cond +=
         * " and rpp.scoperEntities.entityId=?2"; }
         * if(StrUtil.isNotEmpty(empId)) { cond
         * +=" and rpp.playerEntities.entityId=?3 "; }
         * 
         * Query query = em.createQuery(jbql.toString()+cond);
         * if(StrUtil.isNotEmpty(encounterType)) { query.setParameter(1,
         * encounterType); } if(StrUtil.isNotEmpty(deptId)) {
         * query.setParameter(2, Long.parseLong(deptId)); }
         * if(StrUtil.isNotEmpty(empId)) { query.setParameter(3,
         * Long.parseLong(empId)); } List list = query.getResultList();
         */
        return null;
    }


    @SuppressWarnings("unchecked")
    public PatientEncounter findPatientEncounterByPatId(String patientId, String encounterType) throws Hl7Exception
    {
        if (patientId == null)
            return null;
        PatientEncounter patientEncounter = null;
        StringBuilder jbql = new StringBuilder();
        jbql.append("select rp from RimCoreActPrtcptns rp where rp.roleParticipation.roleId=?1 and rp.participationAct.codeEtsId=?2 ");
        Query query = em.createQuery(jbql.toString());
        query.setParameter(1, Long.parseLong(patientId));
        if (StrUtil.isNotEmpty(encounterType))
        {
            query.setParameter(2, encounterType);
        }
        List<RimCoreActPrtcptns> list = query.getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            RimCoreActPrtcptns rimCoreActPrtcptns = list.get(0);
            patientEncounter = (PatientEncounter) rimCoreActPrtcptns.getParticipationAct();
            return patientEncounter;
        }
        return null;
    }

}
